package org.lq.sm.view.sales;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import org.lq.sm.entity.Employee;
import org.lq.sm.entity.Goods;
import org.lq.sm.entity.SalesOrder;
import org.lq.sm.entity.SalesOrderStatus;
import org.lq.sm.entity.Vip;
import org.lq.sm.service.GoodsService;
import org.lq.sm.service.SalesOrderService;
import org.lq.sm.service.iml.GoodsServiceImpl;
import org.lq.sm.service.iml.SalesOrderServiceImpl;
import org.lq.sm.util.CastUtil;
import org.lq.sm.util.ConverToChinesePart;
import org.lq.sm.util.VoicePlay;
import org.lq.sm.view.goods.V_goods;
import org.lq.sm.view.vip.V_vipAdd;

public class V_settlement extends JPanel {

	private v_salesGoods salesGoods;
	private List<Goods> goodsList=new ArrayList<>();
	private JLabel lbl_count;
	private JLabel lbl_totalPrice;
	private JLabel lab_count;
	private JLabel lab_actual;
	private JLabel lab_returnMoney;
	/**
	 * Create the panel.
	 */
	public V_settlement() {

		JLabel label = new JLabel("编号\\拼音+回车确认:");

		JTextField textPane = new JTextField();
		textPane.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode()==10) {
					//创建商品选择窗口
					V_goods goods = new V_goods(textPane.getText());
					//					goods.setBounds(V_settlement.this.getX(), V_settlement.this.getY(), goods.getWidth(), goods.getHeight());
					goods.setVisible(true);

					goods.addWindowListener(new WindowAdapter() {
						public void windowClosed(WindowEvent e) {

							Goods g = new GoodsServiceImpl().getById(goods.getGoodsId());
							Employee emp = (Employee) salesGoods.getCb_emp().getSelectedItem();
							JTable tabGoods = salesGoods.getTab_sales();
							DefaultTableModel dtm = (DefaultTableModel) tabGoods.getModel();
							boolean existence = false;
							for (Goods goods : goodsList) {
								if(g.getGoods_number().equals(goods.getGoods_number())) {
									goods.setCount(goods.getCount()+1);
									existence = true;
									break;
								}
							}
							if(existence == false) {
								goodsList.add(g);
							}
							int rowCount = dtm.getRowCount();
							for (int i = 0; i < rowCount; i++) {
								dtm.removeRow(0);
							}
							//将集合中的商品,循环添加到购物表格中
							for (Goods g2 : goodsList) {
								dtm.addRow(new Object[] {
										g2.getGoods_number(),
										g2.getName(),
										g2.getCount(),
										g2.getSell_price(),
										g2.getSell_price(),
										g2.getCount()*g.getSell_price(),
										g2.getCount()*g.getIntegral(),
										emp,
										g2.getNote()
								});
							}
							initTotal();
						};
					});
				}


			}
		});
		textPane.setFont(new Font("宋体", Font.PLAIN, 36));

		JButton btnNewButton = new JButton("选择");
		btnNewButton.setIcon(new ImageIcon(V_settlement.class.getResource("/images/search.png")));

		JButton button = new JButton("￥结算");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				String total = lbl_totalPrice.getText();
				String price = total.substring(1);
				double totalPrice = CastUtil.castDouble(price);

				V_payment pay = new V_payment(totalPrice);
				pay.setVisible(true);


				pay.addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosed(WindowEvent e) {
						SalesOrderService sos = new SalesOrderServiceImpl();
						GoodsService gs = new GoodsServiceImpl();
						SalesOrder so = new SalesOrder();
						for (Goods goods : goodsList) {
							Employee emp = (Employee) salesGoods.getCb_emp().getSelectedItem();
							so.setCount(goods.getCount());
							so.setEid(emp.getEmpid());
							so.setGid(goods.getId());
							so.setIntegral(goods.getIntegral()*goods.getCount());
							so.setOrderid(salesGoods.getLbl_no().getText());
							so.setPrice(goods.getSell_price());
							so.setStatus(SalesOrderStatus.结算);
							Vip v = salesGoods.getVip();
							if(v!=null) {
								so.setVid(v.getNo());
							}
							so.setTotalPrice(goods.getSell_price()*goods.getCount());
							if(sos.save(so)) {
								goods.setInventory(goods.getInventory()-so.getCount());
								gs.updateGoods(goods);
							}
						}

						salesGoods.clear();
						textPane.setText("");
						lab_count.setText("上单数量:"+goodsList.size());
						lab_actual.setText("应收 : ￥"+pay.getActual());
						lab_returnMoney.setText("找零 : ￥"+pay.getActual());

					}
				});

				Thread playThread = new Thread(()->{
					//数字转换
					ConverToChinesePart ctc = new ConverToChinesePart(totalPrice);
					String voiceStr = ctc.convertToChinese();
					String dir = System.getProperty("user.dir");
					//播放声音
					VoicePlay.play(dir+"/MEDIA/总计.wav");
					for (int i = 0; i < voiceStr.length(); i++) {
						VoicePlay.play(dir+"/MEDIA/"+voiceStr.charAt(i)+".wav");
					}
				});
				playThread.start();
			}
		});
		button.setFont(new Font("宋体", Font.BOLD, 12));

		lab_count = new JLabel("上单数量：6件");

		lab_actual = new JLabel("实收：￥66");

		lab_returnMoney = new JLabel("找零：￥0");

		JButton button_1 = new JButton("新增会员");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				V_vipAdd add = new V_vipAdd();
				add.setVisible(true);
			}
		});

		JButton button_1_1 = new JButton("挂单");
		button_1_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				String total = lbl_totalPrice.getText();
				String price = total.substring(1);
				double totalPrice = CastUtil.castDouble(price);
				SalesOrderService sos = new SalesOrderServiceImpl();
				GoodsService gs = new GoodsServiceImpl();
				SalesOrder so = new SalesOrder();
				for (Goods goods : goodsList) {
					Employee emp = (Employee) salesGoods.getCb_emp().getSelectedItem();
					so.setCount(goods.getCount());
					so.setEid(emp.getEmpid());
					so.setGid(goods.getId());
					so.setIntegral(goods.getIntegral()*goods.getCount());
					so.setOrderid(salesGoods.getLbl_no().getText());
					so.setPrice(goods.getSell_price());
					so.setStatus(SalesOrderStatus.挂单);
					Vip v = salesGoods.getVip();
					if(v!=null) {
						so.setVid(v.getNo());
					}
					so.setTotalPrice(goods.getSell_price()*goods.getCount());
					if(sos.save(so)) {
						goods.setInventory(goods.getInventory()-so.getCount());
						gs.updateGoods(goods);
					}
				}

				salesGoods.clear();
				textPane.setText("");
				lab_count.setText("上单数量:"+goodsList.size());
				lab_actual.setText("应收 : ￥"+0);
				lab_returnMoney.setText("找零 : ￥"+0);

			}
		});

		JButton button_1_1_1 = new JButton("取单");
		button_1_1_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				v_salesDocumens sd = new v_salesDocumens();
				sd.setVisible(true);
				sd.addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosed(WindowEvent e) {
						SalesOrderService sos = new SalesOrderServiceImpl();
						salesGoods.clear();
						List<SalesOrder> saleOrderList = sd.getSaleOrderList();
						salesGoods.getCb_emp().setSelectedItem(saleOrderList.get(0).getEmp());
						salesGoods.showVip(saleOrderList.get(0).getVip());
						 DefaultTableModel  dtm = (DefaultTableModel) salesGoods.getTab_sales().getModel();
						 for (SalesOrder salesOrder : saleOrderList) {
							 goodsList.add(salesOrder.getGoods());
							 dtm.addRow(new Object[] {
									 salesOrder.getGoods().getGoods_number(),
									 salesOrder.getGoods().getName(),
									 salesOrder.getCount(),
									 salesOrder.getGoods().getSell_price(),
									 salesOrder.getGoods().getSell_price(),
									 salesOrder.getPrice()*salesOrder.getCount(),
									 salesOrder.getIntegral(),
									 salesOrder.getEmp().getName(),
									 salesOrder.getGoods().getNote()
							 });
							 sos.delete(salesOrder.getId());
						}
					}
				});
				
			}
		});

		JButton button_1_1_2 = new JButton("无码销售");

		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0)));

		JLabel label_4 = new JLabel("数量 ：");

		lbl_count = new JLabel("0");
		GroupLayout groupLayout = new GroupLayout(this);
		groupLayout.setHorizontalGroup(
				groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
						.addContainerGap()
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addGroup(groupLayout.createSequentialGroup()
										.addComponent(textPane, GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(btnNewButton, GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(button, GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE))
								.addComponent(label)
								.addGroup(groupLayout.createSequentialGroup()
										.addComponent(lab_count)
										.addGap(18)
										.addComponent(lab_actual)
										.addGap(18)
										.addComponent(lab_returnMoney)))
						.addPreferredGap(ComponentPlacement.RELATED)
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(button_1, GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
								.addComponent(button_1_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(button_1_1_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(button_1_1_2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addGroup(groupLayout.createSequentialGroup()
										.addGap(18)
										.addComponent(panel, GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
										.addContainerGap())
								.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(label_4)
										.addGap(18)
										.addComponent(lbl_count)
										.addGap(41))))
				);
		groupLayout.setVerticalGroup(
				groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
						.addContainerGap()
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addGroup(groupLayout.createSequentialGroup()
										.addComponent(panel, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)
										.addGap(18)
										.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
												.addComponent(label_4)
												.addComponent(lbl_count))
										.addGap(38))
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addGroup(groupLayout.createSequentialGroup()
												.addComponent(label)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
														.addComponent(button, GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
														.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
																.addComponent(btnNewButton, GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
																.addComponent(textPane, GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)))
												.addGap(18)
												.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
														.addComponent(lab_count)
														.addComponent(lab_actual)
														.addComponent(lab_returnMoney))
												.addGap(40))
										.addGroup(groupLayout.createSequentialGroup()
												.addComponent(button_1)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(button_1_1)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(button_1_1_1)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(button_1_1_2)
												.addContainerGap()))))
				);
		panel.setLayout(new BorderLayout(0, 0));

		lbl_totalPrice = new JLabel("￥0");
		lbl_totalPrice.setFont(new Font("宋体", Font.BOLD, 36));
		lbl_totalPrice.setHorizontalAlignment(SwingConstants.RIGHT);
		panel.add(lbl_totalPrice, BorderLayout.CENTER);
		setLayout(groupLayout);

	}

	public V_settlement(v_salesGoods panel) {
		this();
		this.salesGoods = panel;
	}




	/*
	 * 窗体整合
	 * 文件导入导出
	 * 项目打包
	 * 系统开发
	 * 数据库备份
	 * 统计报表
	 */



	public void initTotal() {
		double totalPrice = 0;
		for (Goods goods : goodsList) {
			totalPrice += goods.getCount()*goods.getSell_price();
		}
		lbl_totalPrice.setText("￥"+totalPrice);
		lbl_count.setText(salesGoods.getTab_sales().getRowCount()+"");
	}










}
